<?php

namespace app\service;


use app\model\TaskModel;
use app\tool\SingletonTrait;

class WorkbenchUserHistoryService
{

    use SingletonTrait;

    public function __construct()
    {
    }

    /**
     * 统计任务同属
     * @param $userIds
     * @param $startTime
     * @param $endTime
     * @param $timeType
     * @param $projectId
     * @return array
     */
    public function taskCount($userIds, $startTime, $endTime, $timeType, $projectId): array
    {
        $closedId = StatusService::getInstance()->byCode('closed')['id'];
        $query = (new TaskModel)
            ->whereFieldRaw('task.step_type', '<>', TaskModel::STEP_TYPE_STEP_CATEGORY)
            ->whereFieldRaw("get_json_string(task.`json`,'$.task_status')", '<>', $closedId);
        $query = $this->taskFieldCountWhere($query, $userIds, $startTime, $endTime, $timeType, $projectId);
        $query = $query->select();
        if (empty($query->toArray())) {
            return [];
        }
        return array_map(function ($tmp) {
            $tmp['number'] = intval($tmp['number']);
            return $tmp;
        }, $query->toArray());
    }

    /**
     * @param $query
     * @param $userIds
     * @param $startTime
     * @param $endTime
     * @param $timeType
     * @param $projectId
     * @return mixed
     */
    public function taskFieldCountWhere($query, $userIds, $startTime, $endTime, $timeType, $projectId)
    {
        if (!empty($userIds)) {
            $query->join('task_member', 'task_member.task_id = task.id')->whereIn("task_member.partner", $userIds);
        }
        if ($timeType == 'plan_end_time') {
            if (!empty($startTime)) {
                $query->whereFieldRaw('task.plan_end_time', '>=', $startTime);
            }
            if (!empty($endTime)) {
                $query->whereFieldRaw('task.plan_end_time', '<=', $endTime);
            }
            $query->field([
                "count(*) as number",
                "from_unixtime(task.plan_end_time,'%Y-%m-%d') as end_time"
            ])->group("from_unixtime(task.plan_end_time,'%Y-%m-%d')");
        }
        if ($timeType == 'end_time') {
            if (!empty($startTime)) {
                $query->whereFieldRaw('task.end_time', '>=', $startTime);
            }
            if (!empty($endTime)) {
                $query->whereFieldRaw('task.end_time', '<=', $endTime);
            }
            $query->field([
                "count(*) as number",
                "from_unixtime(task.end_time,'%Y-%m-%d') as end_time"
            ])->group("from_unixtime(task.plan_end_time,'%Y-%m-%d')");
        }
        if (!empty($projectId)) {
            $query->where("task.project_id", $projectId);
        }
        return $query;
    }

}
